package com.notebook.utils;

import com.notebook.entity.vo.news.GetNewsVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;


/**
 * 文件描述:
 * 创建用户:emotion
 * 创建时间:2018/3/10
 */
public class GetNewsSources {

    private static final String APPKEY = "9c79bfbd848d5832";
    private static final String URL = "http://api.jisuapi.com/news/get";

    /**
     * 获取uri上的新闻资源
     *
     * @param channel 新闻频道(头条,财经,体育,娱乐,军事,教育,科技,NBA,股票,星座,女性,健康,育儿)
     * @param num     获取新闻的数量
     * @throws Exception
     */
    public static List<GetNewsVO> GetNews(String channel, int num) throws Exception {

        String url = URL + "?channel=" + URLEncoder.encode(channel, "utf-8") + "&num=" + num + "&appkey=" + APPKEY;
        List<GetNewsVO> getNewsVOS = new ArrayList<GetNewsVO>(0);
        try {
            InputStream is = new URL(url).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            StringBuilder sb = new StringBuilder();
            int cp;
            while ((cp = rd.read()) != -1) {
                sb.append((char) cp);
            }
            String jsonText = sb.toString();
            JSONObject jsonObject = JSONObject.fromObject(jsonText);
            JSONObject resultarr = (JSONObject) jsonObject.opt("result");
            JSONArray list = resultarr.optJSONArray("list");

            for (int i = 0; i < list.size(); i++) {
                JSONObject obj = (JSONObject) list.opt(i);
                String title = obj.getString("title");//获取标题
                String content = obj.getString("pic") + obj.getString("content"); //获取新闻内容
                String newsType = resultarr.getString("channel");//获取新闻类别
                String time = obj.getString("time");//获取新闻时间
                String key = StringUtils.InterceptString(title); //新闻关键字等于标题
                GetNewsVO getNewsVO = new GetNewsVO(title, content, newsType, time, key);
                getNewsVOS.add(getNewsVO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getNewsVOS;
    }

}